<template>
  <div>
    <AuFormModal
      ref="formRef"
      v-model="showModal"
      :title="title"
      :formList="formList"
      :formData="selfFormData"
      :modalProps="{
        width: 600,
        position: 'center'
      }"
      :formProps="{
        class: '!w-[546px]'
      }"
      @handleConfirm="handleConfirm"
    >
      <!--      <template #account_label="{ label }">-->
      <!--        <span>{{ label }}</span>-->
      <!--        <el-tooltip-->
      <!--          effect="dark"-->
      <!--          content="新建完成后不可修改账号名称"-->
      <!--          placement="top"-->
      <!--        >-->
      <!--          <IconifyIconOnline-->
      <!--            icon="ls:info"-->
      <!--            class="ml-1 align-middle cursor-pointer"-->
      <!--          />-->
      <!--        </el-tooltip>-->
      <!--      </template>-->
      <!--      <template #email_label="{ label }">-->
      <!--        <span>{{ label }}</span>-->
      <!--        <el-tooltip effect="dark" content="用于账号验证、通知" placement="top">-->
      <!--          <IconifyIconOnline-->
      <!--            icon="ls:info"-->
      <!--            class="ml-1 align-middle cursor-pointer"-->
      <!--          />-->
      <!--        </el-tooltip>-->
      <!--      </template>-->
      <template #post_behind>
        <el-button type="primary" class="w-[140px]" @click="showPost"
          >{{ t("account_manage.form.add_post") }}
        </el-button>
      </template>
    </AuFormModal>

    <PostModal
      v-model="showPostModal"
      :formData="formPostData"
      @submit="getPostList"
    />
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  nextTick,
  onBeforeMount,
  onMounted,
  ref,
  toRef,
  watch
} from "vue";
import { BaseProps, inputProps, selectProps } from "@/components/AuForm/type";
import { AuFormModal } from "@/components/AuModal";
import { storeGroupSelect } from "@/utils/formSelect";
import {
  accountAdd,
  AccountProp,
  accountUpd,
  postGetList
} from "@/api/teaInfuser/account";
import { isArray } from "@pureadmin/utils";
import { cloneDeep } from "lodash-unified";
import PostModal from "@/views/teaInfuser/account/roleManage/PostModal.vue";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";

const { t } = useI18n();

interface Props {
  modelValue: boolean;
  formData?: Partial<AccountProp>;
}

type FormListProp = [
  inputProps,
  // inputProps,
  // inputProps,
  inputProps,
  inputProps,
  BaseProps,
  selectProps
];

const props = withDefaults(defineProps<Props>(), {
  modelValue: false
});
const emit = defineEmits(["update:modelValue", "submit"]);

const title = ref(t("account_manage.form.add_account"));
const formList = ref<FormListProp>([
  {
    type: "input",
    key: "account",
    label: "account_manage.form.account_name",
    placeholder: "account_manage.form.enter_account_name",
    required: true
  },
  // {
  //   type: "input",
  //   key: "realname",
  //   label: "真实姓名",
  //   placeholder: "使用者真实姓名，最多允许输入10个汉字（20字符）",
  //   required: true
  // },
  {
    type: "input",
    key: "phone",
    label: "account_manage.form.phone",
    placeholder: "account_manage.form.enter_phone",
    required: true,
    rules: [
      {
        pattern: /^\+?[1-9]\d{1,14}$/,
        message: t("account_manage.form.phone_format"),
        trigger: "blur"
      }
    ]
  },
  // {
  //   type: "input",
  //   key: "email",
  //   label: "邮箱",
  //   placeholder: "请输入使用者邮箱",
  //   rules: [
  //     {
  //       required: true,
  //       message: "请输入邮箱",
  //       trigger: "blur"
  //     },
  //     {
  //       pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
  //       message: "请输入正确的邮箱",
  //       trigger: "blur"
  //     }
  //   ]
  // },
  {
    type: "input",
    key: "password",
    label: "account_manage.form.password",
    placeholder: "account_manage.form.password_placeholder",
    inType: "password",
    required: true,
    showPassword: true,
    autocomplete: "new-password",
    rules: [
      {
        pattern: /^(?![^a-zA-Z]+$)(?!\D+$).{8,15}$/,
        message: t("account_manage.form.password_format"),
        trigger: "blur"
      }
    ]
  },
  {
    type: "input",
    key: "group_idlist",
    label: "account_manage.form.select_post"
  },
  // () => storeGroupSelect("group_idlist", { checkStrictly: false }, true),
  {
    type: "select",
    key: "post",
    label: "account_manage.form.select_post",
    placeholder: "account_manage.form.post_placeholder",
    options: [],
    labelKey: "name",
    valueKey: "id",
    style: {
      width: "calc(100% - 148px)",
      marginRight: "8px"
    },
    required: true
  }
]);
const selfFormData = toRef(props, "formData");
const showModal = computed({
  get() {
    return props.modelValue;
  },
  set(val: boolean) {
    emit("update:modelValue", val);
  }
});
const showPostModal = ref(false);
const formPostData = ref({});

const formRef = ref();

// region ====================================事件的集合
async function getPostList() {
  const params = {
    start_page: 0,
    size: 0,
    type: "1"
  };
  const res = await postGetList(params);
  const list = isArray(res.data) ? res.data : [];
  formRef.value.setFormProps("post", {
    options: list.map(item => ({
      name: item.name,
      id: item.id
    }))
  });
  showPostModal.value = false;
}

const showPost = () => {
  showPostModal.value = true;
};

const editDisabled = () => {
  formRef.value.setFormProps(["account", "email", "password"], {
    account: { disabled: !!props.formData?.id },
    email: { disabled: !!props.formData?.id },
    password: { disabled: !!props.formData?.id }
  });
};

const handleConfirm = () => {
  const data = cloneDeep(formRef.value.getFormData());
  let service = null;
  if (data.group_idlist?.length) {
    const groupList = data.group_idlist.map((item: number) => ({
      group_id: item
    }));
    data.group_idlist = JSON.stringify(groupList);
  }

  data.realname = "无";
  // data.email = "@";
  if (!data.id) {
    service = accountAdd;
    data.type = "1"; // 商家
    data.department = 1; // 部门
    data.store_idlist = JSON.stringify([]);
    data.account_region_status = false;
    data.account_super_status = false;
    data.account_svip_status = false;
    data.log_share_status = false;
  } else {
    service = accountUpd;
  }
  service(data).then(res => {
    if (res.code === 200) {
      emit("submit");
      ElMessage.success(
        t(
          data.id
            ? "account_manage.form.edit_success"
            : "account_manage.form.add_success"
        )
      );
      formRef.value.reset();
      emit("update:modelValue", false);
    }
  });
};

// endregion

onBeforeMount(async () => {
  formList.value[3] = await storeGroupSelect(
    "group_idlist",
    { checkStrictly: false },
    true
  );
});

watch(
  () => [showModal.value, props.formData],
  ([val, row]: [boolean, AccountProp]) => {
    if (val) {
      // debugger;
      title.value = row?.id
        ? t("account_manage.form.edit_account")
        : t("account_manage.form.add_account");
      const rowData = cloneDeep(row) as AccountProp & {
        group_idlist: number[];
      };
      if (rowData.accountstore_list) {
        rowData.group_idlist = rowData.accountstore_list.map(
          item => item.group_id
        );
      }
      // selfFormData.value = rowData;
      nextTick(async () => {
        await getPostList();
        formRef.value.setFormData(rowData);
        editDisabled();
      });
    } else {
      formRef.value.reset();
    }
  }
);
</script>
